package com.love.cloud.common.mybatis.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;

/**
 * mybatis-plus的自动填充执行器
 * @author hongdongqu
 * @since 2020-10-25
 */
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
    /**
     * 插入时的填充策略
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        boolean hasCreateTime=metaObject.hasSetter("createTime");
        boolean hasUpdateTime=metaObject.hasSetter("updateTime");

        if(hasCreateTime){
            Object val=getFieldValByName("createTime",metaObject);
            if(val==null){
                this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
            }
        }
        if(hasUpdateTime){
            Object val=getFieldValByName("updateTime",metaObject);
            if(val==null){
                this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
            }
        }
    }

    /**
     * 更新时的填充策略
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        boolean hasUpdateTime=metaObject.hasSetter("updateTime");
        if(hasUpdateTime) {
            //更新时间必须要强制设置
            this.setFieldValByName("updateTime",LocalDateTime.now(),metaObject);
        }
    }
}
